package com.currentcms.client.component;

import java.util.List;

import com.currentcms.client.ICellRenderer;
import com.currentcms.client.IEditor;
import com.currentcms.client.event.AddEvent;
import com.currentcms.client.event.AddHandler;
import com.currentcms.client.event.ChangeValueEvent;
import com.currentcms.client.event.ChangeValueHandler;
import com.currentcms.client.event.HasAddHandlers;
import com.currentcms.client.event.HasChangeValueHandlers;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Widget;

public class AddListEditor<T> extends FlowPanel implements HasAddHandlers, HasChangeValueHandlers, IEditor<List<T>>
{
	private final HandlerManager handlerManager = new HandlerManager(this);

	private ListEditor<T> listEditor;
	private Button addButton;

	public AddListEditor(String title, boolean reorderable, boolean deletable, boolean confirmDelete)
	{
		listEditor = new ListEditor<T>(reorderable, deletable, confirmDelete);
		listEditor.setWidth("100%");
		listEditor.addChangeValueHandler(new ChangeValueHandler()
		{
			public void onChangeValueEvent(ChangeValueEvent event)
			{
				handlerManager.fireEvent(event);
			}
		});
		addButton = new Button("Edit " + title);
		addButton.addClickHandler(new ClickHandler()
		{
			@Override
			public void onClick(ClickEvent event)
			{
				handlerManager.fireEvent(new AddEvent(AddListEditor.this));
			}
		});

		add(listEditor);
		add(addButton);
	}

	public Widget getAddButton()
	{
		return addButton;
	}

	public Widget addValue(T o)
	{
		listEditor.setDirty(true);
		return listEditor.addValue(o);
	}

	@Override
	public HandlerRegistration addAddHandler(AddHandler handler)
	{
		return handlerManager.addHandler(AddEvent.getType(), handler);
	}

	@Override
	public HandlerRegistration addChangeValueHandler(ChangeValueHandler handler)
	{
		return handlerManager.addHandler(ChangeValueEvent.getType(), handler);
	}

	@Override
	public void setValue(List<T> o)
	{
		listEditor.setValue(o);
	}
	
	@Override
	public List<T> getValue()
	{
		return listEditor.getValue();
	}

	@Override
	public boolean getDirty()
	{
		return listEditor.getDirty();
	}

	@Override
	public void setDirty(boolean dirty)
	{
		listEditor.setDirty(dirty);
	}
	
	public void setCellRenderer(ICellRenderer<T> cell_renderer)
	{
		listEditor.setCellRenderer(cell_renderer);
	}
}
